<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

require_once "Curl.php";
require_once "RequestCheckUtil.php";

class TopClientException extends ThinkException
{
}


class TopClient
{
	private $appkey = TB_AKEY;

    private $secretKey = TB_SKEY;

	public $gatewayUrl = API_REQUEST_CONTAINER;
	
	public $format = "json";

	public $checkRequest = true;

	protected $signMethod = "md5";

	protected $apiVersion = "2.0";

	protected $sdkVersion = "top-sdk-php-20151012";

	protected function generateSign($params)
	{
		ksort($params);

		$stringToBeSigned = $this->secretKey;
		foreach ($params as $k => $v)
		{
			if("@" != substr($v, 0, 1))
			{
				$stringToBeSigned .= "$k$v";
			}
		}
		unset($k, $v);
		$stringToBeSigned .= $this->secretKey;

		return strtoupper(md5($stringToBeSigned));
	}

	public function curl($url, $postFields = null)
	{
		$http = new Curl();
		if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https") {
			$http->setOpt(CURLOPT_SSL_VERIFYPEER, false);
			$http->setOpt(CURLOPT_SSL_VERIFYHOST, false);
		}
		
		$http->post($url, $postFields);
		
		return $http->response;
	}

	public function execute($request, $session = null)
	{
		if($this->checkRequest) {
			// try {  // we throw exception directly and will catch it at the top level
				$request->check();
			// } catch (Exception $e) {
			// 	$result->code = $e->getCode();
			// 	$result->msg = $e->getMessage();
			// 	return $result;
			// }
		}
		//组装系统参数
		$sysParams["app_key"] = $this->appkey;
		$sysParams["v"] = $this->apiVersion;
		$sysParams["format"] = $this->format;
		$sysParams["sign_method"] = $this->signMethod;
		$sysParams["method"] = $request->getApiMethodName();
		$sysParams["timestamp"] = date("Y-m-d H:i:s");


		if (null != $session)
		{
			$sysParams["session"] = $session;
		}

		//获取业务参数
		$apiParams = $request->getApiParas();
		
		//合并参数
		$allParams = array_merge($apiParams, $sysParams);
        $sign = $this->generateSign($allParams);
        $allParams["sign"] = $sign;
		//系统参数放入GET请求串 , depresssed as POST请求
		$requestUrl = $this->gatewayUrl;
		//发起HTTP请求. 尝试5次，如果仍然有问题就直接抛出异常. 
		$try_times = 5 ;
		$wait_time = 300000;
		while( $try_times > 0 ) {
			$resp = $this->curl($requestUrl, $allParams);
			if(!$resp) {
				return;
			}
			if(IS_CLI) {
				usleep(100000);
			}	
			//解析TOP返回结果
			$respWellFormed = false;
			if ("json" == $this->format) {
				$respObject = json_decode($resp);
				if (null !== $respObject) {
					$respWellFormed = true;
					foreach ($respObject as $propKey => $propValue) {
						$respObject = $propValue;
					}
				}
			} else if("xml" == $this->format) {
				$respObject = @simplexml_load_string($resp);
				if (false !== $respObject) {
					$respWellFormed = true;
				}
			}
	
			//返回的HTTP文本不是标准JSON或者XML，记下错误日志
			if (false === $respWellFormed) {
				throw new TopClientException( '返回的结果不是有效的JSON或者XML. 请求的时间戳: ' . time() . '. 请求的URI: ' .  $requestUrl.'.返回结果：'.$resp);
			}
	
			//如果TOP返回了错误码，记录到业务错误日志中
			if (isset($respObject->code)) {   
			    $data = array(
			            	'req_resp' => $resp
			    		);
			    if($try_times) {
			    	
				    	//当错误为7的时候进行特殊处理，可以重新请求
				    	//当错误为15，而且{"error_response":{"code":15,"msg":"Remote service error","sub_code":"isp.top-remote-connection-timeout"}}，可以重新请求
				    	
					    if(($respObject->code == 7) || 
					    		($respObject->code == 15 && substr($respObject->sub_code, 0, 3) == 'isp')) {
					    	--$try_times;
					    	usleep($wait_time);
					    	$wait_time *=  2;
							continue;
					    }
			    }
			    if($respObject->code == 15 && $allParams['method'] == "taobao.simba.adgroup.add") {
			    	return array();
			    } else {
				    //其他错误直接排除原版resp的json字符串
				    throw new TopClientException( $resp );
				}
			}
			
			//如果无错误则break退出while循环返回结果
			break;
		}
		
		return $respObject;
	}

	public function exec($paramsArray)
	{
		if(!isset($paramsArray["method"])) {
			trigger_error("No api name passed");
		}
		$inflector = new LtInflector;
		$inflector->conf["separator"] = ".";
		$requestClassName = ucfirst($inflector->camelize(substr($paramsArray["method"], 7))) . "Request";
		if(!class_exists($requestClassName)) {
			trigger_error("No such api: " . $paramsArray["method"]);
		}

		$session = isset($paramsArray["session"]) ? $paramsArray["session"] : null;

		$req = new $requestClassName;
		foreach($paramsArray as $paraKey => $paraValue) {
			$inflector->conf["separator"] = "_";
			$setterMethodName = $inflector->camelize($paraKey);
			$inflector->conf["separator"] = ".";
			$setterMethodName = "set" . $inflector->camelize($setterMethodName);
			if (method_exists($req, $setterMethodName)) {
				$req->$setterMethodName($paraValue);
			}
		}
		return $this->execute($req, $session);
	}
    
    public static function init($request = null)
    {
        if($request) {
            $file =  dirname(__FILE__) .  DS . "request" . DS . $request . ".php"; 
            if(file_exists($file)){
                require_once $file;
                return new $request;
            }
        }
        
        return false;
    }

    public function setAppkey($appkey, $appSecret)
	{
		$this->appkey = $appkey;
		$this->secretKey = $appSecret;
	}

	public function getAppKey()
	{
		return $this->appkey;
	}
}
